package com.research.demo.toolkit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class ConfigHelper {
    private static Logger log = LoggerFactory.getLogger(ConfigHelper.class);

    /**
     * 根据指定的key获取对应的配置值
     */
    public static String getByKey(String path, String key) {
        Map<String, String> map = getProps(path);
        if (!map.isEmpty()) {
            return map.get(key);
        }
        return null;
    }

    /**
     * 获取配置文件键值对
     */
    private static Map<String, String> getProps(String path) {
        Properties prop = new Properties();
        Map<String, String> props = new HashMap<>();
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(path));
            prop.load(in);
            Enumeration names = prop.propertyNames();

            while (names.hasMoreElements()) {
                String name = (String)names.nextElement();
                props.put(name, prop.getProperty(name));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return props;
    }
}
